package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tensquare.common.auth.constant.AuthorityCode;
import com.tensquare.common.util.JwtUtil;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: WangYaWei
 * @description:
 * @create: 2019-08-29 17:35
 **/
@Component
public class ManagerPreFilter extends ZuulFilter{
    @Autowired
    private JwtUtil jwtUtill;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //传递header中的token
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();

        if(request.getMethod().equals("OPTION")){
            return null;
        }

        //登录地址放行
        if(request.getRequestURL().toString().indexOf("/admin/login") != -1){
            return null;
        }


        String authorization = request.getHeader("Authorization");
        if(authorization != null && authorization.startsWith("Bearer ")){
            Claims claims = jwtUtill.parseJwt(authorization.substring(7));
            if(AuthorityCode.ADMIN.equals(claims.get("roles"))){
                //管理员权限放行
                requestContext.addZuulRequestHeader("Authorization", authorization);
                return null;
            }
        }

        requestContext.setSendZuulResponse(false);//终止运行
        requestContext.setResponseStatusCode(401);
        response.setContentType("text/json;charset=UTF-8");
        try {
            response.getWriter().write("{\"flag\":false,\"code\":"+ StatusCode.ACCESS_ERROR +", \"message\":\"权限不足\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
